import os.path
import sys
import matplotlib.pyplot as plt
import numpy as np
from generate_analyseWLs import get_csv_names

# 好像已经放弃使用了？
raise ValueError
csv_names, sizes = get_csv_names()

mem = 0
for i in range(5, 15):
    mem = mem + sizes[i]
print(mem)

# 这一段分析的时候才加
# plt.subplot(121)
# plt.plot(sizes)
# plt.title(len(sizes))
# plt.subplot(122)
# mem = [3*np.array(sizes[:i]).sum() for i in range(len(sizes))]
# plt.plot(mem)
# plt.xlabel('samples to accumulate')
# plt.ylabel('approximate mem in GB')
# plt.show()

START = int(sys.argv[1])
STEP = int(sys.argv[2])

f = open('./scripts/concurrent_run' + str(START) + '_' + str(STEP) + '.sh', 'w')
sys.stdout = f

print('#!/bin/bash')
print('start_time=$(date +%s)\n')

filenames = ''
for i in range(STEP):
    filenames += csv_names[START+i] + ' '

print('#', START, STEP)

with open('./scripts/concurrent_filenames' + str(START) + '_' + str(STEP) + '.txt', 'w') as f:
    f.writelines(filenames)

NUM_OPS_PERIOD = 10000000
if not os.path.exists('../evaluation_analyse/'):
    os.mkdir('../evaluation_analyse/')


print('sync; echo 3 | sudo tee /proc/sys/vm/drop_caches')
cmd = ''
for i in range(STEP):
    cmd += "sudo ./scripts/run_lsm_one.sh %s & " %csv_names[START+i]
print(cmd)
print('wait\necho run_lsm完成\n')

print('sync; echo 3 | sudo tee /proc/sys/vm/drop_caches')
cmd = ''
for i in range(STEP):
    cmd += "sudo ./scripts/run_baseline_one.sh %s & " %csv_names[START+i]
print(cmd)
print('wait\necho run_baseline完成\n')

print('# 下面的是统计性能，fork自all_trace.sh')
print('path=../data/ebs_segment_io_records/AY283G_2022-01-01_00:00:00_2022-01-02_00:00:00/device/\n')


print('for filename in %s; do' % filenames)
print('  data_path=${path}${filename}')
print('  data_name=${filename%.*}')
print('  for executable_file in trace_allGet trace_realRun ; do')
print('    python ./scripts/collect_results.py 1 ${data_name}_${executable_file}_16 > ../evaluation/expr_${data_name}_${executable_file}_16.txt &')
print('  done')
print('done')
print('wait\n')


print('for filename in %s; do' % filenames)
print('  data_path=${path}${filename}')
print('  data_name=${filename%.*}')
print('  for executable_file in trace_allGet trace_realRun ; do')
print('    cat ../evaluation/expr_${data_name}_${executable_file}_16.txt')
print('  done')
print('  # plot iteration decay')
print('  python ./scripts/plot2_iterationDecay.py ${data_name}')
print('done\n')

# print('# 整体的plot')
# print('python ./scripts/plot3_mean_and_speedUp.py', START, STEP)

print('\n# 结束，统计时间')
print('end_time=$(date +%s)')
print('cost_time=$((end_time-start_time))')
print('echo "$0" "运行时间：$((cost_time/60))min $((cost_time%60))s"')
new_evaluation_global = '../evaluation_global_' + filenames.split()[0].split('.')[0] + '_' + str(START) + '_' + str(STEP) + 'tr/'
print("newpath=%s" % new_evaluation_global)
print("if [ ! -d ${newpath} ]; then")
print('  mkdir %s' % new_evaluation_global)
print("fi")
print('mv %s %s' % ('../evaluation_global/*', new_evaluation_global))
f.close()
